﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Castle.MicroKernel;
using System.Web.Routing;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.MicroKernel.SubSystems.Configuration;

namespace EventPlanner
{
    /// <summary>
    /// Controller Factory de aplicación
    /// </summary>
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {                
                controllerType = typeof(EventPlanner.Controllers.HomeController);
            }
            return (IController)kernel.Resolve(controllerType);
        }
    }

    /// <summary>
    /// Installer
    /// </summary>
    public class WindsorInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {            
            container.Register(FindControllers().Configure(comp => comp.LifestyleTransient()));
            container.Register(Component.For<EventPlanner.Models.IEventPlannerContext>()
                .ImplementedBy<EventPlanner.Models.EventPlannerContext>().LifeStyle.Transient);            
        }

        private BasedOnDescriptor FindControllers()
        {
            return AllTypes.FromThisAssembly()
            .BasedOn<IController>()
            .If(Component.IsInSameNamespaceAs<EventPlanner.Controllers.HomeController>())
            .If(t => t.Name.EndsWith("Controller"));
        }
    }

}